package com.esoon.smartsee;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.ExceptionHandler;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.rabbitmq.client.AMQP.PROTOCOL.PORT;

public class TestActivity extends AppCompatActivity {

    @BindView(R.id.sendbutton)
    Button button;
    @BindView(R.id.mqtext)
    EditText editText;
   static Handler handler;



    private String userName = "mcu";
    private String passWord = "bnp@1234";
    private String hostName = "47.103.45.89";
    private int portNum = 5672;
    private String exchangeName = "amq.direct";
    private static final String TAG = "TestActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        ButterKnife.bind(this);


        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                switch (msg.what) {
                    case 1:
                        Log.e(TAG, "Recieved msg is :" + msg.obj);
                        break;
                    case 2:
                        break;

                }

            }
        };


        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(() -> {
                    basicPublish();
                }).start();

                new Thread(() -> {
                    basicConsume();
                }).start();
            }
        });

    }


    private void basicPublish() {

        try {
            ConnectionFactory factory;
            factory = new ConnectionFactory();
            factory.setHost(hostName);//ip地址
            factory.setPort(portNum);//端口号
            factory.setUsername(userName);
            factory.setPassword(passWord);
            factory.setVirtualHost("vms");

            //连接
            Connection connection;
            Channel channel;
            connection = factory.newConnection();
            //通道
            channel = connection.createChannel();
            //消息发布
            byte[] msg = "hello girl friend!".getBytes();
            //rountingKey 自己任意填写
            channel.queueDeclare("queue_" + "10009", false, false, false, null);
            channel.basicPublish(exchangeName, "key_" + "10009", null, msg);

            Log.e(TAG, "sending msg");
            channel.close();
            connection.close();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }

    }

    private void basicConsume() {

        try {
            //连接
            ConnectionFactory factory;
            factory = new ConnectionFactory();
            factory.setHost(hostName);//ip地址
            factory.setPort(portNum);//端口号
            factory.setUsername(userName);
            factory.setPassword(passWord);
            factory.setVirtualHost("vms");

            Connection connection = factory.newConnection();
            //通道
            final Channel channel = connection.createChannel();
            //声明了一个交换和一个服务器命名的队列，然后将它们绑定在一起。
            channel.exchangeDeclare(exchangeName, "fanout", true);
            String queueName = channel.queueDeclare().getQueue();
            Log.e("TAG", queueName + " :queueName");
            channel.queueBind(queueName, exchangeName, "key_" + "10009");
            //实现Consumer的最简单方法是将便捷类DefaultConsumer子类化。可以在basicConsume 调用上传递此子类的对象以设置订阅：
            channel.basicConsume(queueName, false, "administrator", new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    super.handleDelivery(consumerTag, envelope, properties, body);

                    String rountingKey = envelope.getRoutingKey();//路由密钥
                    String contentType = properties.getContentType();//contentType字段，如果尚未设置字段，则为null。
                    String msg = null;//接收到的消息
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                        msg = new String(body, StandardCharsets.UTF_8);
                    }
                    Message message = new Message();
                    message.what = 1;
                    message.obj = msg;
                    handler.sendMessage(message);
                    long deliveryTag = envelope.getDeliveryTag();//交付标记

                    Log.e("TAG", rountingKey + "：rountingKey");
                    Log.e("TAG", contentType + "：contentType");
                    Log.e("TAG", msg + "：msg");
                    Log.e("TAG", deliveryTag + "：deliveryTag");
                    Log.e("TAG", consumerTag + "：consumerTag");
                    Log.e("TAG", envelope.getExchange() + "：exchangeName");

                    channel.basicAck(deliveryTag, false);
                }
            });

        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }

    }


}
